<template>
  <div class="page-mobile-my-task">
      <white-header :isShowTopNav="true" :isShowBack="true" :isShowRight="true" title="我的作业"></white-header>
      <div class="my_task">
        <div class="no-data" v-if="myTaskList.length == 0">
          <van-empty description="暂时没有作业哦~" />
        </div>
        <!-- <ul class="my_task_list" v-if="false">
          <li class="task_item" v-for="(item,index) in myTaskList" :key="item.id">
            <div class="task_item_left">
              <img :src="item.courseIcon" alt="">
            </div>
            <div class="task_item_right">
              <p>{{item.taskName}}</p>
              <div class="task_btn_list">
                <van-button type="primary" size="small" v-if="item.resourceUrl" @click="downloadResource(item.resourceUrl, item.taskName)">下载资源</van-button>
                <van-button type="primary" size="small" v-else disabled>暂无资源</van-button>
                <van-button type="primary" size="small" @click="examineHandle(item)">审批流程</van-button>
                <van-button type="primary" size="small" @click="introduceHandle(item.introduce)">注意事项</van-button>
              </div>
              <Upload
                class="avatar-uploader"
                ref="avatar-uploader"
                action=""
                :before-upload="afterRead"
                :show-file-list="false"
                :auto-upload="false"
                :show-upload-list="false"
                @click="false"
                 v-if="item.taskType == 2"
              >
                <van-button type="primary" size="small" class="submit_btn"  @click="setTask(item)" :disabled="!!item.userTask">{{item.userTask ? "已经上传":"上传作业"}}</van-button>
              </Upload>
              <van-button type="primary" size="small" class="submit_btn"  @click="setTask(item)" :disabled="!!item.userTask" v-else>{{item.userTask ? "考试完成":"开始考试"}}</van-button>
            </div>
          </li>
        </ul> -->
        <ul class="my_task_list_content">
          <li class="task_item_box" v-for="(item,index) in myTaskList" :key="item.id">
            <div class="task_title">
              作业{{index+1}}《{{item.videoName}}》
            </div>
            <div class="task_center">
              <p class="task_name">{{item.taskName}}</p>
              <p class="task_time">有效时间：{{item.startTime}}至{{item.endTime}}</p>
              <div class="task_btn_list">
                <div  v-if="item.resourceUrl" @click="downloadResource(item.resourceUrl, item.taskName)" :class="['btn_item', 'bg_blue']">下载资源</div>
                <div  v-else :class="['btn_item', 'bg_blue']">暂无资源</div>
                <div  @click="examineHandle(item)" :class="['btn_item', 'bg_blue']" style="margin:0 .24rem;">审批流程</div>
                <Upload
                class="avatar-uploader"
                ref="avatar-uploader"
                action=""
                :before-upload="afterRead"
                :show-file-list="false"
                :auto-upload="false"
                :show-upload-list="false"
                @click="false"
                 v-if="item.taskType == 2"
              >
                <div  @click="setTask(item,!!item.userTask,$event)" :class="['btn_item', item.userTask ? 'bg_gray' : 'bg_pink']">{{item.userTask ? "已经上传":"上传作业"}}</div>
                </Upload>
                <div  @click="setTask(item,!!item.userTask,$event)" v-else :class="['btn_item', item.userTask ? 'bg_gray' : 'bg_pink']">{{item.userTask ? "考试完成":"开始考试"}}</div>
                
              </div>
              <div class="btn_text" v-if="item.userTask && item.userTask.state == 0">正在审批中...</div>
            </div>
          </li>
        </ul>
      </div>
      <div class="footer" v-if="myTaskList.length != 0 && myTaskList.length === taskPages.total">
          <span class="tips">我是有底线的</span>
      </div>
      <div class="introduce_dialog" v-show="introduceDialog">
        <div class="introduce_box">
          <h3>注意事项</h3>
          <p>{{introduce}}</p>
          <van-icon class="close_introduce_dialog" name="cross" @click="introduceDialog = false" size=".4rem"/>
        </div>
      </div>
      <div class="examine_dialog" v-show="examineDialog">
        <div class="examine_box">
          <h3>审批流程</h3>
          <div v-if="examineObj.current === 0">
            <van-icon name="info" class="icon_examine" size="1.4rem"/>
            <template v-if="examineObj && examineObj.taskType == 1">
              <p>您尚未开始考试哟 !</p>
            </template>
            <template  v-if="examineObj && examineObj.taskType == 2">
              <p>您尚未上传课程作业哟 !</p>
            </template>
          </div>
          <div v-if="examineObj.current === 1">
            <van-icon name="column" class="icon_examine" size="1.4rem"/>
            <p>您的课程作业正在审批中</p>
            <p>请耐心等待哟 !</p>
          </div>
          <div v-if="examineObj.current === 2">
            <template v-if="examineObj && examineObj.state == 1">
              <van-icon name="checked" class="icon_examine" size="1.4rem"  color="var(--theme-color)"/>
              <p>恭喜您，您的课程作业已经及格了哟 !</p>
            </template>
            <template  v-if="examineObj && examineObj.state == 2">
              <van-icon name="clear" class="icon_examine" size="1.4rem"  color="#ee0a24"/>
              <p>很遗憾，您的课程作业不及格</p>
              <p>请继续努力哟 !</p>
            </template>
          </div>
          <van-icon class="close_examine_dialog" name="cross" @click="examineDialog = false" size=".4rem"/>
        </div>
      </div>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import { getMyTaskList, saveUserTask } from "~/api/task";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import { downloadReport } from "~/api/course";
export default {
  name: "my-task",
  scrollToTop: true,
  components: {
    WhiteHeader
  },
  // head() {
  //   return {
  //     meta: [
  //       {
  //         "http-equiv": "Content-Security-Policy",
  //         content: "upgrade-insecure-requests"
  //       }
  //     ]
  //   };
  // },
  props: ["setDisabled", "refreshFun", "setLoading"],
  data() {
    return {
      myTaskList: [], //作业列表
      taskPages:{
        page: 1,
        pageSize: 5,
        total:0
      },
      introduce:"",
      introduceDialog:false,
      examineDialog:false,
      examineObj:{},
      taskObj:{},
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      is_in_minigram(state) {
        return state.is_in_minigram;
      },
      is_loading(state) {
        return state.is_loading;
      },
    }),
  },
  activated() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
        return;
      }else{
          window.addEventListener("scroll", this.eventListener)
      }
    }
    this.initPages();
    this.setDisabled(false);
    this.refreshFun(() => {
      this.initPages();
      this.setLoading(false);
    });
  },
  deactivated() {
    if (process.client) {
      window.removeEventListener("scroll", this.eventListener);
    }
    this.setDisabled(true);
  },
  destroyed() {
    if (process.client) {
      window.removeEventListener("scroll", this.eventListener);
    }
  },
  watch: {
    course_record_list(new_val, old_val) {
      console.log("new_val:", new_val);
      console.log("old_val:", old_val);
      // if (new_val.length !== old_val.length) {
      //   this.getTestPapers(
      //     new_val.map(i => {
      //       return {
      //         ...i,
      //         courseId: i.id
      //       };
      //     })
      //   );
      // }
    }
  },
  methods: {
    ...mapMutations(["SET_IS_LOADING"]),
    trimDate(date) {
      if (date) {
        let _date = new Date(date);
        var year = _date.getFullYear();
        var month = _date.getMonth() + 1;
        var date = _date.getDate();
        var hours = _date.getHours();
        var minutes = _date.getMinutes();
        if (month < 10) {
          month = "0" + month;
        }
        if (date < 10) {
          date = "0" + date;
        }
        if (hours < 10) {
          hours = "0" + hours;
        }
        if (minutes < 10) {
          minutes = "0" + minutes;
        }
        return year + "." + month + "." + date + " " + hours + ":" + minutes;
        // return `${_date.getFullYear()}.${_date.getMonth() +
        //   1}.${_date.getDate()} ${_date.getHours()}:${'0'+_date.getMinutes()}`;
      } else {
        return this.$t("locale.pc.classroom.unknow");
      }
    },
    introduceHandle(introduce){
      this.introduce = introduce ? introduce : '暂无注意事项';
      this.introduceDialog = true;
    },
    examineHandle(item){
      console.log(item);
      if(item.userTask && Object.keys(item.userTask).length > 0){
        if(item.userTask.state === 0){
          this.examineObj = {
            current:1,
            taskType:item.taskType,
          }
        }else{
          this.examineObj = {
            current:2,
            state:item.userTask.state,
            taskType:item.taskType,
          }
        }
      }else{
        this.examineObj = {
          current:0,
          taskType:item.taskType,
        }
      }
      this.examineDialog = true;
    },
     //设置我的作业报告的数据
    setTask(obj,status,event){
      if(status){
        event.stopPropagation();
        return;
      }
      if(obj && obj.taskType == 2){
        this.taskObj = obj;
      }else{
        console.log("跳转");
        this.$router.push('/m/task-paper?taskId='+ obj.id)
      }
    },
    afterRead(file) {
      let params = {
        userId: this.user_info.id,
        file: file,
        taskId:this.taskObj.id
      };
      this.uploadFile(params);
      return false;
    },
    async uploadFile(params){
        this.SET_IS_LOADING(true);
        console.log(params);
        let fd = new FormData();
        Object.keys(params).forEach(i => {
            if(params[i] || params[i] === 0){
                fd.append(i, params[i]);
            }
        });
        let result = await saveUserTask(fd);
        if (result && result.data && result.data.code == 200) {
            this.$toast("上传作业成功！");
            this.getMyTask();
        }else if(result && result.data && result.data.code == 1001){
          this.$toast(result.data.msg);
        }else {
          this.$toast("上传作业失败！");
        }
        this.SET_IS_LOADING(false);
        return false;
    },
    async downloadResource(url, taskName) {
      // 如果是小程序内
      /* 在小程序环境下载文件 */
      if (this.is_in_minigram) {
        wx.miniProgram.navigateTo({
          url: `/pages/download/index?downloadUrl=${url}`,
          success: function() {
            console.log("成功跳转小程序");
          },
          fail: function() {
            console.log("跳转小程序失败");
          },
          complete: function() {
            console.log("完成");
          }
        });
        /* 调起微信小程序 */
        return;
      }
      this.SET_IS_LOADING(true);

      let result = await downloadReport(url);
      const content = result.data;
      const blob = new Blob([content]);
      let fileName = taskName + "." + url.replace(/(.*\.)/, ""); // 自定义文件名+后缀;
      if ("download" in document.createElement("a")) {
        console.log("非IE下载");
        // 非IE下载
        const elink = document.createElement("a");
        elink.download = fileName;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      } else {
        // IE10+下载
        console.log("IE10+下载");
        navigator.msSaveBlob(content, fileName);
      }
      this.SET_IS_LOADING(false);
    },
    eventListener() {
      this.throttle(this.pullUp, 300);
    },
    throttle(fn, delay) {
      let lastTime = 0;
      return !(function () {
        let nowTime = Date.now();
        if (nowTime - lastTime > delay) {
          fn.call(this);
          lastTime = nowTime;
        }
      })();
    },
    pullUp() {
      // 滚动条离顶部的距离
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 窗口可视区域高度
      let clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      // 滚动区域高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      // 滚动条 + 可视区域高度 >= 滚动条高度 ==>  滚动条触底
      console.log(scrollTop + "+" + clientHeight + ">=" + scrollHeight);
      //适配处理:-120的是距离底部120px触发上拉加载，而不是触底加载
      if (scrollTop + clientHeight >= scrollHeight - 120) {
        if (this.taskPages.total <= this.myTaskList.length) {
          return;
        }
        if (this.is_loading) {
          return;
        }
        this.taskPages.page++;
        this.getMyTask("pullup");
      }
    },
    async getMyTask(fetch_type){
        this.SET_IS_LOADING(true);
        let params = {
            offset: this.taskPages.pageSize * (this.taskPages.page - 1),
            limit: this.taskPages.pageSize,
            sort: 'id desc',
        }
        let result = await getMyTaskList(params);
        if (result && result.data && result.data.code == 200) {
            if (fetch_type == "pullup") {
                this.myTaskList = [...this.myTaskList, ...result.data.data.rows];
            } else {
                this.myTaskList = result.data.data.rows;
            }
            this.taskPages.total = result.data.data.total;
        }else{
            this.$toast("获取失败！");
        }
        this.SET_IS_LOADING(false);
    },
    initPages() {
      if (process.client) {
        if (!this.token && Object.keys(this.user_info).length == 0) {
          this.$router.replace("/m/login");
          return;
        } else {
          this.taskPages.page = 1;
          this.introduce = "",
          this.introduceDialog = false,
          this.examineDialog = false,
          this.examineObj = {}
          this.getMyTask();
        }
      }
    }
  },
  created() {
    this.setDisabled(false);
    this.initPages();
    this.refreshFun(() => {
      this.initPages();
      this.setLoading(false);
    });
  },
  mounted() {
    
  }
};
</script>

<style lang="scss" scoped>
.page-mobile-my-task {
  min-height: 100vh;
  // min-height: calc(100vh - 1.6rem);
  background-color: #f9f8f8;
  padding: 0 0 0.2rem 0;
  .introduce_dialog{
    position: fixed;
    top: 0;
    left: 0;
    z-index: 2013;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    .introduce_box{
      position: fixed;
      top: 3rem;
      left: 0;
      right: 0;
      margin: auto;
      min-height: 3rem;
      width: 6rem;
      overflow: hidden;
      font-size: .3072rem;
      background-color: #fff;
      border-radius: .16rem;
      box-sizing: border-box;
      padding: 0 .2rem .4rem;
      .close_introduce_dialog{
        position: absolute;
        right: .1rem;
        top: .1rem;
      }
      h3{
        text-align: center;
        line-height: .8rem;
        font-size: .4rem;
      }
      p{
        max-height: 5rem;
        overflow: auto;
        line-height: .44rem;
      }
    }
  }
  .examine_dialog{
    position: fixed;
    top: 0;
    left: 0;
    z-index: 2013;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    .examine_box{
      position: fixed;
      top: 3rem;
      left: 0;
      right: 0;
      margin: auto;
      min-height: 3rem;
      width: 6rem;
      overflow: hidden;
      font-size: .3072rem;
      background-color: #fff;
      border-radius: .16rem;
      box-sizing: border-box;
      padding: 0 .6rem .4rem;
      text-align: center;
      .icon_examine{
        margin: .2rem 0;
      }
      .close_examine_dialog{
        position: absolute;
        right: .1rem;
        top: .1rem;
      }
      h3{
        text-align: center;
        line-height: .8rem;
        font-size: .4rem;
      }
      p{
        max-height: 5rem;
        overflow: auto;
        line-height: .44rem;
        text-align: center;
      }
    }
  }
  .my_task{
      .my_task_list{
        .task_item{
          width: 7.2rem;
          height: 2rem;
          background: #fff;
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 0 .26rem;
          border-bottom: 1px solid #babec2;
          &:last-child{
            border-bottom:none;
          }
          .task_item_left{
            >img{
              width: 2.1rem;
              height: 1.4rem;
              display: block;
              border-radius: .06rem;
            }
          }
          .task_item_right{
            width: 4.4rem;
            height: 1.4rem;
            position: relative;
            p{
              font-size: .28rem;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2;
              overflow: hidden;
              height: .672rem;
              width: 3rem;
            }
            .task_btn_list{
              margin-top: .3rem;
              display: flex;
              justify-content: space-between;
            }
            .submit_btn{
              position: absolute;
              right: 0;
              top: 0rem;
            }
          }
        }
        
      }
      .my_task_list_content{
        padding-top: .4608rem;
        .task_item_box{
          width: 6.624rem;
          height: 3.0048rem;
          background-color: #ffffff;
          border-radius: .192rem;
          margin:0 auto .192rem;
          .task_title{
            padding: .288rem .1727rem .16rem;
            box-sizing: border-box;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
            font-size: .2688rem;
            font-weight: bold;
            color: #43474c;
            letter-spacing: .0288rem;
          }
          .task_center{
            padding: 0 .288rem;
            .task_name{
              font-size: .2688rem;
              font-weight: bold;
              color: var(--theme-color);
              letter-spacing: .0288rem;
              text-overflow: ellipsis;
              overflow: hidden;
              white-space: nowrap;
            }
            .task_time{
              font-size: .192rem;
              line-height: .3456rem;
              color: #bcc2cc;
              margin-top: .3rem;
              margin-bottom: .3rem;
            }
            .task_btn_list{
              display: flex;
              justify-content: flex-end;
              // flex-direction: column;
              // align-items: flex-end;
              .btn_item{
                width: 1.2384rem;
                height: .4608rem;
                color: #ffffff;
                border-radius: .096rem;
                font-size: .2304rem;
                text-align: center;
                line-height: .4608rem;
                &.bg_gray{
                  background-color: #d6d6d6;
                }
                &.bg_pink{
                  background-color: #ff8a8a;
                }
                &.bg_blue{
                  background-color: var(--theme-color);
                }
              }
              
            }
            .btn_text{
                margin-top: .1rem;
                line-height: .3rem;
                font-size: .2304rem;
                color: var(--theme-color);
                text-align: right;
              }
          }
          
        }
      }
      
  }
  .footer {
    padding: 0.3rem;
    font-size: 0.26rem;
    color: #babec2;
    text-align: center;
    .tips {
      position: relative;
    }
    .tips::before {
      content: "";
      display: block;
      position: absolute;
      left: -1.7rem;
      top: 50%;
      transform: translateY(-1px);
      width: 1.5rem;
      height: 1px;
      background: #babec2;
    }
    .tips::after {
      content: "";
      display: block;
      position: absolute;
      right: -1.7rem;
      top: 50%;
      width: 1.5rem;
      transform: translateY(-1px);
      height: 1px;
      background: #babec2;
    }
  }
}
</style>
<style lang="scss">
.page-mobile-my-task {
  
}
</style>
